package com.project.mq.mqclient;

import com.project.mq.common.*;
import com.project.mq.mqserver.core.BasicProperties;
import com.project.mq.mqserver.core.ExchangeType;
import lombok.Data;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Data
public class Channel {
    private String channelId;
    private Connection connection;
    // key 为 rid, 即 requestId / responseId.
    //用来存储后续客户端收到的服务器的响应
    private ConcurrentHashMap<String, BaseReturns> baseReturnsMap = new ConcurrentHashMap<>();
    // 订阅消息的回调
    // 如果当前 Channel1 订阅了个队列，就需要在此处记录下对应回调是啥，当该队列的消息返回回来的时候，调用回调。
    // 此处约定一个 Channel1 中只能有一个回调。
    private Consumer consumer = null;

    public Channel(String channelId, Connection connection) {
        this.channelId = channelId;
        this.connection = connection;
    }
    // 在这个方法中，和服务器进行交互，告知服务器，此处客户端创建了新的 channel 了。0x1
    public boolean createChannel() throws IOException {
        BaseArguments baseArguments = new BaseArguments();
        baseArguments.setRid(generateRid());
        baseArguments.setChannelId(channelId);
        byte[] payload = BinaryTool.toBytes(baseArguments);
        // 对于创建 Channel 操作来说，payload 就是一个 basicArguments 对象
        Request request = new Request();
        request.setType(0x1);
        request.setLength(payload.length);
        request.setPayload(payload);
        //构造出完整的请求之后,就可以发送请求了
        connection.writeRequest(request);
        // 阻塞等待服务器的响应
        BaseReturns baseReturns = waitResult(baseArguments.getRid());
        return baseReturns.isOk();
    }
    // 期望使用这个方法来阻塞等待服务器的响应，
    private BaseReturns waitResult(String rid) {
        BaseReturns baseReturns = null;
        while ((baseReturns = baseReturnsMap.get(rid)) == null) {
            // 如果查询结果为 null，说明包裹还没回来。
            // 此时就需要阻塞等待。
            synchronized (this) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    // 如果 wait 被提前唤醒，也应该继续循环.
                    // 所以这里啥都不干，但是 try 需要放到 while 内部.
                    e.printStackTrace();
                }
            }
        }
        // 读取成功之后，还需要把这个消息从哈希表中删除掉。
        baseReturnsMap.remove(rid);
        return baseReturns;
    }

    public void putReturns(BaseReturns baseReturns) {
        baseReturnsMap.put(baseReturns.getRid(), baseReturns);
        synchronized (this) {
            // 这里要唤醒所有等待的线程，不能只唤醒一个。
            notifyAll();
        }
    }

    //rid 也使用 UUID 来生成. 加个前缀 R-
    private String generateRid() {
        return "R-" + UUID.randomUUID().toString();
    }
    // 关闭 channel1，给服务器发送一个 type = 0x2 的请求
    public boolean close() throws IOException {
        // 删除服务器上的 channel. 如果不显式调用, 也没关系. 服务器会在 Connection 断开的时候统一回收.
        BaseArguments baseArguments = new BaseArguments();
        baseArguments.setRid(generateRid());
        baseArguments.setChannelId(channelId);
        byte[] payload = BinaryTool.toBytes(baseArguments);
        Request request = new Request();
        request.setType(0x2);
        request.setLength(payload.length);
        request.setPayload(payload);
        connection.writeRequest(request);
        // 阻塞等待服务器的响应
        BaseReturns baseReturns = waitResult(baseArguments.getRid());
        return baseReturns.isOk();
    }
    //创建交换机 0X3
    public boolean exchangeDeclare(String exchangeName, ExchangeType exchangeType,
                                   boolean durable, boolean autoDelete,
                                   Map<String, Object> arguments) throws IOException {
        ExchangeDeclareArguments exchangeDeclareArguments = new ExchangeDeclareArguments();
        exchangeDeclareArguments.setRid(generateRid());
        exchangeDeclareArguments.setChannelId(channelId);
        exchangeDeclareArguments.setExchangeName(exchangeName);
        exchangeDeclareArguments.setExchangeType(exchangeType);
        exchangeDeclareArguments.setDurable(durable);
        exchangeDeclareArguments.setAutoDelete(autoDelete);
        exchangeDeclareArguments.setArguments(arguments);
        byte[] payload = BinaryTool.toBytes(exchangeDeclareArguments);

        Request request = new Request();
        request.setType(0x3);
        request.setLength(payload.length);
        request.setPayload(payload);
        connection.writeRequest(request);

        // 阻塞等待服务器的响应
        BaseReturns baseReturns = waitResult(exchangeDeclareArguments.getRid());
        return baseReturns.isOk();
    }
    //删除交换机 0x4
    public boolean exchangeDelete(String exchangeName) throws IOException {
        ExchangeDeleteArguments exchangeDeleteArguments = new ExchangeDeleteArguments();
        exchangeDeleteArguments.setRid(generateRid());
        exchangeDeleteArguments.setChannelId(channelId);
        exchangeDeleteArguments.setExchangeName(exchangeName);
        byte[] payload = BinaryTool.toBytes(exchangeDeleteArguments);

        Request request = new Request();
        request.setType(0x4);
        request.setLength(payload.length);
        request.setPayload(payload);
        connection.writeRequest(request);

        // 阻塞等待服务器的响应
        BaseReturns baseReturns = waitResult(exchangeDeleteArguments.getRid());
        return baseReturns.isOk();
    }
    //创建对列 0x5
    public boolean queueDeclare(String queueName, boolean durable, boolean exclusive, boolean autoDelete,
                                Map<String, Object> arguments) throws IOException {
        QueueDeclareArguments queueDeclareArguments = new QueueDeclareArguments();
        queueDeclareArguments.setRid(generateRid());
        queueDeclareArguments.setChannelId(channelId);
        queueDeclareArguments.setQueueName(queueName);
        queueDeclareArguments.setDurable(durable);
        queueDeclareArguments.setExclusive(exclusive);
        queueDeclareArguments.setAutoDelete(autoDelete);
        queueDeclareArguments.setArguments(arguments);
        byte[] payload = BinaryTool.toBytes(queueDeclareArguments);

        Request request = new Request();
        request.setType(0x5);
        request.setLength(payload.length);
        request.setPayload(payload);
        connection.writeRequest(request);

        // 阻塞等待服务器的响应
        BaseReturns baseReturns = waitResult(queueDeclareArguments.getRid());
        return baseReturns.isOk();
    }
    //删除对列 0x6
    public boolean queueDelete(String queueName) throws IOException {
        QueueDeleteArguments queueDeleteArguments = new QueueDeleteArguments();
        queueDeleteArguments.setRid(generateRid());
        queueDeleteArguments.setChannelId(channelId);
        queueDeleteArguments.setQueueName(queueName);
        byte[] payload = BinaryTool.toBytes(queueDeleteArguments);

        Request request = new Request();
        request.setType(0x6);
        request.setLength(payload.length);
        request.setPayload(payload);
        connection.writeRequest(request);

        // 阻塞等待服务器的响应
        BaseReturns baseReturns = waitResult(queueDeleteArguments.getRid());
        return baseReturns.isOk();
    }
    //创建绑定 0x7
    // 对于直接交换机和 fanout 交换机, bindingKey 不生效. 直接设为 "" 即可
    public boolean queueBind(String queueName, String exchangeName) throws IOException {
        return queueBind(queueName, exchangeName, "");
    }
    public boolean queueBind(String queueName, String exchangeName, String bindingKey) throws IOException {
        QueueBindArguments queueBindArguments = new QueueBindArguments();
        queueBindArguments.setRid(generateRid());
        queueBindArguments.setChannelId(channelId);
        queueBindArguments.setQueueName(queueName);
        queueBindArguments.setExchangeName(exchangeName);
        queueBindArguments.setBindingKey(bindingKey);
        byte[] payload = BinaryTool.toBytes(queueBindArguments);

        Request request = new Request();
        request.setType(0x7);
        request.setLength(payload.length);
        request.setPayload(payload);
        connection.writeRequest(request);

        // 阻塞等待服务器的响应
        BaseReturns baseReturns = waitResult(queueBindArguments.getRid());
        return baseReturns.isOk();
    }

    //删除绑定 0x8
    public boolean queueUnbind(String queueName, String exchangeName) throws IOException {
        QueueUnbindArguments queueUnbindArguments = new QueueUnbindArguments();
        queueUnbindArguments.setRid(generateRid());
        queueUnbindArguments.setChannelId(channelId);
        queueUnbindArguments.setQueueName(queueName);
        queueUnbindArguments.setExchangeName(exchangeName);
        byte[] payload = BinaryTool.toBytes(queueUnbindArguments);

        Request request = new Request();
        request.setType(0x8);
        request.setLength(payload.length);
        request.setPayload(payload);
        connection.writeRequest(request);

        // 阻塞等待服务器的响应
        BaseReturns baseReturns = waitResult(queueUnbindArguments.getRid());
        return baseReturns.isOk();
    }
    //发送消息 0x9
    public boolean basicPublish(String exchangeName, String routingKey,
                                BasicProperties basicProperties, byte[] body) throws IOException {
        BasicPublishArguments basicPublishArguments = new BasicPublishArguments();
        basicPublishArguments.setRid(generateRid());
        basicPublishArguments.setChannelId(channelId);
        basicPublishArguments.setExchangeName(exchangeName);
        basicPublishArguments.setRoutingKey(routingKey);
        basicPublishArguments.setBasicProperties(basicProperties);
        basicPublishArguments.setBody(body);
        byte[] payload = BinaryTool.toBytes(basicPublishArguments);

        Request request = new Request();
        request.setType(0x9);
        request.setLength(payload.length);
        request.setPayload(payload);
        connection.writeRequest(request);

        // 阻塞等待服务器的响应
        BaseReturns baseReturns = waitResult(basicPublishArguments.getRid());
        return baseReturns.isOk();
    }
    //订阅消息 0xa
    public boolean basicConsume(String queueName, boolean autoAck, Consumer consumer) throws IOException, MqException {
        // 设置回调
        if (this.consumer != null) {
            throw new MqException("该 channel 已经设置过消费回调，不能重复设置!");
        }
        this.consumer = consumer;

        BasicConsumeArguments basicConsumeArguments = new BasicConsumeArguments();
        basicConsumeArguments.setRid(generateRid());
        basicConsumeArguments.setChannelId(channelId);
        basicConsumeArguments.setQueueName(queueName);
        basicConsumeArguments.setAutoAck(autoAck);
        // 此处 consumerTag 也使用 channelId 来表示了。
        basicConsumeArguments.setConsumeTag(channelId);
        byte[] payload = BinaryTool.toBytes(basicConsumeArguments);

        Request request = new Request();
        request.setType(0xa);
        request.setLength(payload.length);
        request.setPayload(payload);
        connection.writeRequest(request);

        // 阻塞等待服务器的响应
        BaseReturns baseReturns = waitResult(basicConsumeArguments.getRid());
        return baseReturns.isOk();
    }
    //确认消息 0xb
    public boolean basicAck(String queueName, String messageId) throws IOException {
        BasicAckArguments basicAckArguments = new BasicAckArguments();
        basicAckArguments.setRid(generateRid());
        basicAckArguments.setChannelId(channelId);
        basicAckArguments.setQueueName(queueName);
        basicAckArguments.setMessageId(messageId);
        byte[] payload = BinaryTool.toBytes(basicAckArguments);

        Request request = new Request();
        request.setType(0xb);
        request.setLength(payload.length);
        request.setPayload(payload);
        connection.writeRequest(request);

        // 阻塞等待服务器的响应
        BaseReturns baseReturns = waitResult(basicAckArguments.getRid());
        return baseReturns.isOk();
    }
}